/*
 FuelCalc -- calculates the average fuel consumption
 Copyright (C) 2007 Grzegorz Błaszczyk Consulting (www.albatros.pl)

 This file is part of Grzegorz Błaszczyk Consulting code.

 GNU FuelCalc is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2, or (at your option)
 any later version.

 GNU FuelCalc is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with GNU FuelCalc; see the file COPYING. If not, write to the
 Grzegorz Błaszczyk Consuling

 Linking this library statically or dynamically with other modules is
 making a combined work based on this library. Thus, the terms and
 conditions of the GNU General Public License cover the whole
 combination.

 As a special exception, the copyright holders of this library give you
 permission to link this library with independent modules to produce an
 executable, regardless of the license terms of these independent
 modules, and to copy and distribute the resulting executable under
 terms of your choice, provided that you also meet, for each linked
 independent module, the terms and conditions of the license of that
 module. An independent module is a module which is not derived from
 or based on this library. If you modify this library, you may extend
 this exception to your version of the library, but you are not
 obligated to do so. If you do not wish to do so, delete this
 exception statement from your version. 
 */

package gbc.fuelcalc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * FuelCalc
 */
public class FuelCalc {

    private static final String PROGRAM_NAME = "FuelCalc";

    /**
     * Calculates average fuel consumption based upon the following parameters,
     * 
     * @param fuelMoney
     *            amount of money spent on fuel in PLN
     * @param distance
     *            in km
     * @param fuelPrice
     *            price of 1 liter of fuel in PLN
     */
    private static float calculateAverageFuelConsumption(float fuelMoney,
            float distance, float fuelPrice) {
        return ((fuelMoney * 100) / (distance * fuelPrice));
    }

    private static void printLogo(ResourceBundle bundle) {
        try {
            System.out.println(bundle.getString("main.programName") + " v"
                    + bundle.getString("main.programVersion"));
        } catch (MissingResourceException e) {
            System.err.println("Resource is missing: " + e);
        }
    }

    private static void printUsage(ResourceBundle bundle) {
        try {
            System.out
                    .println(bundle.getString("main.usage") + ": "
                            + PROGRAM_NAME + " "
                            + bundle.getString("main.parametersExample"));
        } catch (MissingResourceException e) {
            System.err.println("Resource is missing: " + e);
        }
    }

    private static float[] parseParameters(String[] args) {

        float[] params = new float[3];

        if ("-m".equals(args[0])) {
            try {
                params[0] = new Float(args[1]).floatValue();
            } catch (NumberFormatException e) {
                System.err.println("Error reading -m parameter");
                System.exit(1);
            }
        }

        if ("-p".equals(args[2])) {
            try {
                params[1] = new Float(args[3]).floatValue();
            } catch (NumberFormatException e) {
                System.err.println("Error reading -p parameter");
                System.exit(1);
            }
        }

        if ("-d".equals(args[4])) {
            try {
                params[2] = new Float(args[5]).floatValue();
            } catch (NumberFormatException e) {
                System.err.println("Error reading -d parameter");
                System.exit(1);
            }
        }
        return params;
    }

    public static void main(String[] args) {

        ResourceBundle bundle = loadBundle();

        if (bundle != null) {

            printLogo(bundle);

            float[] params = new float[3];

            if (args == null || args.length == 0) {
                params = fetchParameters(bundle);
            } else if (args != null && args.length < 6) {
                printUsage(bundle);
            } else {
                params = parseParameters(args);
            }

            if (params[0] != 0) {
                float avg = calculateAverageFuelConsumption(params[0],
                        params[2], params[1]);

                avg *= 100;
                avg = (float) Math.round(avg) / 100;

                System.out.println(bundle
                        .getString("main.averageFuelConsumption")
                        + ": " + avg + " l/100km");
            }
        }

    }

    private static float[] fetchParameters(ResourceBundle bundle) {
        float[] params = new float[3];

        try {

            while (params[0] == 0 || params[1] == 0 || params[2] == 0) {

                if (params[0] == 0) {
                    params[0] = fetchParameter(bundle, "main.fuelMoneyInput");
                } else if (params[1] == 0) {
                    params[1] = fetchParameter(bundle, "main.fuelPriceInput");
                } else if (params[2] == 0) {
                    params[2] = fetchParameter(bundle, "main.distanceInput");
                }
            }
        } catch (MissingResourceException e) {
            System.err.println("Resource is missing: " + e);
        }
        return params;
    }
    
    private static float fetchParameter(ResourceBundle bundle, String bundleKey) {
        float param = 0;
        String input = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(
                System.in));
        
        try {
        
            System.out.print(bundle.getString(bundleKey) + ": ");
            try {
                input = br.readLine();
            } catch (IOException ioe) {
                System.err.println(bundle.getString("main.invalidValue"));
            }
            
            try {
                param = new Float(input).floatValue();
            } catch (NumberFormatException e) {
                System.err.println(bundle.getString("main.invalidValue"));
            }
        } catch (MissingResourceException e) {
            System.err.println("Resource is missing: " + e);
        }
        
        return param;
    }

    private static ResourceBundle loadBundle() {
        ResourceBundle rb = null;
        try {
            rb = ResourceBundle.getBundle("gbc.fuelcalc.resources");
        } catch (MissingResourceException e) {
            System.err.println("Missing resource bundle" + e);
        }
        return rb;

    }

}
